package com.yochi.pictureseditor.tools;

import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

import android.util.Log;

public class JsonSerializer {
	
	private static final String TAG = "JsonSerializer";
	
	/**
	 * Serialize the given object to JSON format, using org.codehaus.jackson library.
	 * @param objectToSerialize
	 * @return JSON formatted String
	 */
	public static String serialize(Object objectToSerialize) {
	    Writer strWriter = new StringWriter();
	    ObjectMapper mapper = new ObjectMapper();
	    try { 
	    	mapper.writeValue(strWriter, objectToSerialize);
		} catch (JsonGenerationException e) { 
			Log.e(TAG, e.toString());
		} catch (JsonMappingException e) { 
			Log.e(TAG, e.toString());
		} catch (IOException e) { 
			Log.e(TAG, e.toString()); 
		}
	    return strWriter.toString();
	}
	

	/**
	 * Deserialize the given JSON formatted string to the given class object,
	 * using org.codehaus.jackson library.
	 * @param jsonFormattedString
	 * @param classObject
	 * @return result object. Could be null if exception catched.
	 */
	public static Object deserialize(String jsonFormattedString, Class<?> classObject) {
		ObjectMapper mapper = new ObjectMapper();
		Object result = null;
		try {
			result = mapper.readValue(jsonFormattedString, classObject);
		} catch (JsonParseException e) {
			Log.e(TAG, e.toString());
		} catch (JsonMappingException e) {
			Log.e(TAG, e.toString());
		} catch (IOException e) {
			Log.e(TAG, e.toString());
		}
		return result;
	}

}
